<template>
  <div class="video-player-container">
    <!-- 视频元素 -->
    <video ref="videoRef" :src="videoSrc" :poster="poster" class="video-player"
           @loadedmetadata="onLoadedMetadata" @timeupdate="onTimeUpdate"
           @ended="onVideoEnded" @click="togglePlay">
    </video>

    <!-- 控制栏 -->
    <div class="controls" :class="{ hidden: !showControls && !isHovering }">
      <div class="controls-buttons">
        <el-space>
          <!-- 播放/暂停按钮 -->
          <button class="control-btn" @click.stop="togglePlay">
            <i class="fas" :class="isPlaying ? 'fa-pause' : 'fa-play'"></i>
          </button>
          <!-- 时间显示 -->
          <div class="time-display">
            {{ formatTime(currentTime) }} / {{ formatTime(duration) }}
          </div>
        </el-space>
        <!-- 进度条 -->
        <div class="progress-container" @click="seek">
          <div class="progress-bar" :style="{ width: `${progress}%` }"></div>
          <div class="progress-handle" :style="{ left: `${progress}%` }"></div>
        </div>
        <el-space>
          <!-- 音量控制 -->
          <div class="volume-wrapper"
               @mouseenter="handleVolumeEnter"
               @mouseleave="handleVolumeLeave">
            <button class="control-btn" @click.stop="toggleMute">
              <i class="fas" :class="isMuted ? 'fa-volume-mute' : 'fa-volume-up'"></i>
            </button>

            <!-- 纵向音量滑动器 -->
            <div ref="volumeSliderRef" class="volume-slider vertical" v-if="showVolumeSlider">
              <input
                  type="range"
                  min="0"
                  max="1"
                  step="0.05"
                  v-model="volume"
                  @input="setVolume"
                  class="vertical-slider"
              >
            </div>
          </div>
          <!-- 播放速度 -->
          <div class="playback-rate" @click.stop="toggleRateMenu">
            <button class="control-btn">
              {{ playbackRate }}x
            </button>
            <div class="rate-menu" v-if="showRateMenu">
              <div
                  v-for="rate in playbackRates"
                  :key="rate"
                  class="rate-option"
                  @click.stop="setPlaybackRate(rate)"
              >
                {{ rate }}x
              </div>
            </div>
          </div>

          <!-- 全屏按钮 -->
          <button class="control-btn" @click.stop="toggleFullScreen">
            <i class="fas" :class="isFullScreen ? 'fa-compress' : 'fa-expand'"></i>
          </button>
        </el-space>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, watch, onBeforeUnmount } from 'vue';

// 组件属性
const props = defineProps({
  videoSrc: {
    type: String,
    required: true
  },
  poster: {
    type: String,
    default: ''
  }
});

// 视频元素引用
let videoRef = ref(null);
const volumeSliderRef = ref(null); // 音量滑动器引用

// 播放状态
const isPlaying = ref(false);
const duration = ref(0);
const currentTime = ref(0);
const progress = ref(0);
const volume = ref(1);
const isMuted = ref(false);
const playbackRate = ref(1);
const playbackRates = [0.5, 0.75, 1, 1.25, 1.5, 2];
const showControls = ref(true);
const isHovering = ref(false);
const showVolumeSlider = ref(false);
const showRateMenu = ref(false);
const isFullScreen = ref(false);

// 计时器ID
let controlsTimer = null;
let volumeHideTimer = null; // 音量滑动器隐藏延迟计时器

// 格式化时间
const formatTime = (time) => {
  const minutes = Math.floor(time / 60);
  const seconds = Math.floor(time % 60);
  return `${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`;
};

// 视频元数据加载完成
const onLoadedMetadata = () => {
  duration.value = videoRef.value.duration;
};

// 视频播放时间更新
const onTimeUpdate = () => {
  currentTime.value = videoRef.value.currentTime;
  progress.value = (currentTime.value / duration.value) * 100;
};

// 视频播放结束
const onVideoEnded = () => {
  isPlaying.value = false;
};

// 切换播放/暂停
const togglePlay = () => {
  if (isPlaying.value) {
    videoRef.value.pause();
  } else {
    videoRef.value.play();
  }
  isPlaying.value = !isPlaying.value;
  resetControlsTimer();
};

// 进度条点击跳转
const seek = (e) => {
  const rect = e.currentTarget.getBoundingClientRect();
  const pos = (e.clientX - rect.left) / rect.width;
  const newTime = pos * duration.value;
  videoRef.value.currentTime = newTime;
  currentTime.value = newTime;
  progress.value = pos * 100;
  resetControlsTimer();
};

// 切换静音
const toggleMute = () => {
  videoRef.value.muted = !isMuted.value;
  isMuted.value = !isMuted.value;
  resetControlsTimer();
};

// 设置音量
const setVolume = () => {
  videoRef.value.volume = volume.value;
  if (isMuted.value && volume.value > 0) {
    isMuted.value = false;
    videoRef.value.muted = false;
  }
  resetControlsTimer();
};

// 切换播放速度菜单
const toggleRateMenu = () => {
  showRateMenu.value = !showRateMenu.value;
  resetControlsTimer();
};

// 设置播放速度
const setPlaybackRate = (rate) => {
  videoRef.value.playbackRate = rate;
  playbackRate.value = rate;
  showRateMenu.value = false;
  resetControlsTimer();
};

// 切换全屏
const toggleFullScreen = () => {
  const container = document.querySelector('.video-player-container');
  if (!document.fullscreenElement) {
    container.requestFullscreen().catch(err => {
      console.error(`全屏切换错误: ${err.message}`);
    });
    isFullScreen.value = true;
  } else {
    document.exitFullscreen();
    isFullScreen.value = false;
  }
  resetControlsTimer();
};

// 重置控制栏显示计时器
const resetControlsTimer = () => {
  if (controlsTimer) {
    clearTimeout(controlsTimer);
  }
  showControls.value = true;
  if (isPlaying.value) {
    controlsTimer = setTimeout(() => {
      showControls.value = false;
    }, 3000);
  }
};

// 处理音量区域鼠标进入
const handleVolumeEnter = () => {
  // 清除延迟隐藏计时器
  if (volumeHideTimer) {
    clearTimeout(volumeHideTimer);
  }
  showVolumeSlider.value = true;
};

// 处理音量区域鼠标离开
const handleVolumeLeave = (e) => {
  // 检查鼠标是否真的离开音量控制区域（包括滑动器）
  if (volumeSliderRef.value) {
    const sliderRect = volumeSliderRef.value.getBoundingClientRect();
    const isInSlider = (
        e.clientX >= sliderRect.left &&
        e.clientX <= sliderRect.right &&
        e.clientY >= sliderRect.top &&
        e.clientY <= sliderRect.bottom
    );

    // 如果鼠标在滑动器内，不隐藏
    if (isInSlider) return;
  }

  // 添加延迟隐藏，给用户足够时间移动鼠标
  volumeHideTimer = setTimeout(() => {
    showVolumeSlider.value = false;
  }, 300);
};

// 监听全屏状态变化
const handleFullScreenChange = () => {
  isFullScreen.value = !!document.fullscreenElement;
};

// 组件挂载
onMounted(() => {
  // 初始化视频元素事件监听
  videoRef.value.addEventListener('play', () => {
    isPlaying.value = true;
  });

  videoRef.value.addEventListener('pause', () => {
    isPlaying.value = false;
  });

  // 监听全屏状态变化
  document.addEventListener('fullscreenchange', handleFullScreenChange);

  // 设置初始音量
  videoRef.value.volume = volume.value;

  // 设置鼠标悬停状态
  const container = document.querySelector('.video-player-container');
  container.addEventListener('mouseenter', () => {
    isHovering.value = true;
    resetControlsTimer();
  });

  container.addEventListener('mouseleave', () => {
    isHovering.value = false;
  });

  // 监听全局鼠标移动，判断是否在音量滑动器上
  document.addEventListener('mousemove', (e) => {
    if (showVolumeSlider.value && volumeSliderRef.value) {
      const sliderRect = volumeSliderRef.value.getBoundingClientRect();
      const isInSlider = (
          e.clientX >= sliderRect.left &&
          e.clientX <= sliderRect.right &&
          e.clientY >= sliderRect.top &&
          e.clientY <= sliderRect.bottom
      );

      // 如果鼠标在滑动器上，保持显示
      if (isInSlider) {
        if (volumeHideTimer) {
          clearTimeout(volumeHideTimer);
        }
      }
    }
  });
});

// 组件卸载前清理
onBeforeUnmount(() => {
  if (controlsTimer) clearTimeout(controlsTimer);
  if (volumeHideTimer) clearTimeout(volumeHideTimer);
  document.removeEventListener('fullscreenchange', handleFullScreenChange);
});
const pauseVideo = () => {
  if (videoRef.value) {
    videoRef.value.pause();
    isPlaying.value = false;
  }
};

// 暴露方法给父组件
defineExpose({
  pauseVideo
});
// 监听视频源变化，重置播放器
watch(
    () => props.videoSrc,
    () => {
      isPlaying.value = false;
      progress.value = 0;
      currentTime.value = 0;
      duration.value = 0;
    }
);
</script>

<style scoped>
.video-player-container {
  position: relative;
  width: 100%;
  max-width: 1200px;
  margin: 0 auto;
  background-color: #000;
  border-radius: 8px;
  overflow: hidden;
  cursor: pointer;
}

.video-player {
  width: 100%;
  height: auto;
  display: block;
}

.controls-buttons {
  display: flex;
  justify-content: space-between;
}

.controls {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  background: linear-gradient(transparent, rgba(0, 0, 0, 0.8));
  color: white;
  padding: 15px 10px 5px;
  transition: opacity 0.3s ease;
}

.controls.hidden {
  opacity: 0;
}

.progress-container {
  height: 5px;
  background-color: rgba(255, 255, 255, 0.3);
  border-radius: 3px;
  cursor: pointer;
  position: relative;
}

.progress-bar {
  height: 100%;
  background-color: #ff3e3e;
  border-radius: 3px;
  transition: width 0.1s ease;
}

.progress-handle {
  position: absolute;
  top: 50%;
  width: 12px;
  height: 12px;
  background-color: white;
  border-radius: 50%;
  transform: translate(-50%, -50%);
  box-shadow: 0 0 3px rgba(0, 0, 0, 0.5);
  opacity: 0;
  transition: opacity 0.2s ease;
}

.progress-container:hover .progress-handle {
  opacity: 1;
}

.control-btn {
  background: none;
  border: none;
  color: white;
  cursor: pointer;
  font-size: 16px;
  transition: color 0.2s ease;
}

.control-btn:hover {
  color: #ff3e3e;
}

.time-display {
  font-size: 14px;
  min-width: 100px;
}

/* 音量控制区域优化 */
.volume-wrapper {
  position: relative;
  display: inline-flex;
  align-items: center;
  padding: 8px 5px; /* 显著扩大交互区域 */
  margin: 0 -5px;
  z-index: 15;
}

/* 纵向音量滑动器容器 */
.volume-slider.vertical {
  position: absolute;
  bottom: 48px; /* 精确调整位置 */
  left: 50%;
  transform: translateX(-50%);
  width: 40px; /* 更宽的检测区域 */
  height: 120px; /* 更长的滑动区域 */
  padding: 10px 0;
  display: flex;
  align-items: center;
  justify-content: center;
}

/* 纵向滑动条样式 */
.vertical-slider {
  width: 100px;
  height: 6px;
  transform-origin: center;
  transform: rotate(-90deg);
  appearance: none;
  background: rgba(255, 255, 255, 0.3);
  border-radius: 3px;
  outline: none;
  margin: 0;
}

/* 滑动条滑块样式 */
.vertical-slider::-webkit-slider-thumb {
  appearance: none;
  width: 16px;
  height: 16px;
  border-radius: 50%;
  background: #ff3e3e;
  cursor: pointer;
  box-shadow: 0 0 4px rgba(0, 0, 0, 0.5);
  transition: transform 0.1s ease;
}

.vertical-slider::-webkit-slider-thumb:hover {
  transform: scale(1.2);
}

.playback-rate {
  position: relative;
}

.rate-menu {
  position: absolute;
  bottom: 30px;
  left: 0;
  background-color: rgba(0, 0, 0, 0.7);
  border-radius: 4px;
  overflow: hidden;
  z-index: 10;
}

.rate-option {
  padding: 5px 10px;
  cursor: pointer;
  transition: background-color 0.2s ease;
}

.rate-option:hover {
  background-color: rgba(255, 255, 255, 0.2);
}

.rate-option:nth-child(3) {
  background-color: #ff3e3e;
}
</style>
